import React from 'react';
import { connect } from 'dva';
import _ from 'lodash';
import { Table } from 'antd';
import RH from 'react-highcharts';
import Granularity from '../../../components/granularity';
import common from '../common.less';

const mstp = ({ device }) => ({ ...device });

const parseChartData = (data, templateData) => {
    const res = {};
    res.series = _.map(templateData, ({ id, name }) => {
        return {
            name,
            data: [],
            id: id.toString(),
        };
    });
    _.forEach(data, ({ date: name, ...other }) => {
        if (!res.categories) {
            res.categories = [];
        }
        res.categories.push(name);
        _.forEach(other, (v, k) => {
            const target = _.find(res.series, ['id', k]);
            if (target) {
                target.data.push(v);
            }
        });
    });
    return res;
};

export default connect(mstp)((props) => {
    const {
        data,
        searchInfo: { type, value } = {},
        deviceList,
        dispatch
    } = props;

    const columns = [
        {
            title: '时间',
            dataIndex: 'date',
        },
        ..._.map(deviceList, ({ id, name: title }) => ({
            title,
            dataIndex: id.toString(),
        }))
    ];
    const res = parseChartData(data, deviceList);
    const config = {
        title: { text: '设备运行报表' },
        credits: {
            enabled: false,
        },
        xAxis: {
            title: {
                text: '时间',
            },
            categories: res.categories,
            labels: {
                formatter() {
                    return this.value;
                }
            }
        },
        yAxis: {
            title: {
                text: '运行次数(次)',
            },
        },
        series: res.series,
    };

    const onChange = (searchInfo) => {
        dispatch({
            type: 'device/changeSearchType',
            searchInfo,
        });
    };

    return (
        <div className={common.normalWrap}>
            <div className={common.search}>
                <Granularity
                    type={type}
                    value={value}
                    onChange={onChange}
                />
            </div>
            <div className={common.table}>
                <RH config={config} />
                <Table
                    rowKey="code"
                    columns={columns}
                    dataSource={data}
                />
            </div>
        </div>
    );
});
